package net.hn.hnms.biz.equipment.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.feign.model.DataStateVo;
import net.hn.hnms.biz.api.mine.model.AlarmMessageItemVo;
import net.hn.hnms.biz.api.mine.model.FanSystemVolumeAndSpeedDto;
import net.hn.hnms.biz.equipment.domain.CoalMineSysPointPo;
import net.hn.hnms.biz.equipment.domain.EquPointTable;
import net.hn.hnms.biz.equipment.domain.dto.ProductionStatementDto;
import net.hn.hnms.biz.equipment.domain.dto.ProductionStatementEquipmentStartDayDto;
import net.hn.hnms.biz.equipment.domain.vo.*;
import net.hn.hnms.biz.equipment.mapper.CoalMineSysPointMapper;
import net.hn.hnms.biz.equipment.mapper.EquipmentMapper;
import net.hn.hnms.biz.equipment.mapper.EquipmentStartDayMapper;
import net.hn.hnms.biz.equipment.mapper.FanrealNowMapper;
import net.hn.hnms.biz.equipment.service.EquipmentService;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.redis.domain.SysOrganization;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import net.hn.hnms.sys.system.api.domain.SysDictData;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Author: PanSX
 * Date: 2022/8/13 14:49
 */
@Service
@RequiredArgsConstructor
public class EquipmentServiceImpl implements EquipmentService {
    private final EquipmentMapper equipmentMapper;
    private final CoalMineSysPointMapper coalMineSysPointMapper;

    /**
     * 重大设备开机起始mapper
     */
    @Resource
    private EquipmentStartDayMapper equipmentStartDayMapper;

    @Resource
    private FanrealNowMapper fanrealNowMapper;
    Map<String, String> dbName = setDbName();
    Map<String, String> devName = setDevName();

    private Map<String, String> setDbName() {
        Map<String, String> map = new HashMap<>();
        //空压机
        map.put("compressor", "dwd_zdsb_now_compressor");
        //排水
        map.put("drainage", "dwd_zdsb_now_drainage");
        //通风
        map.put("fan", "dwd_zdsb_now_fan");
        //煤流
        map.put("coalflow", "dwd_zdsb_now_coalflow");
        //铁路装车
//        map.put("railway", "dwd_zdsb_now_railway");
        //立井提升
        map.put("shaft", "dwd_zdsb_now_shaft");
        //斜井提升
        map.put("inclineShaft", "dwd_zdsb_now_inclineshaft");
        //支架
        map.put("support", "dwd_zdsb_now_support");
        //采煤
        map.put("mining", "dwd_zdsb_now_mining");
        //协同开采
//        map.put("thermalshock", "dwd_zdsb_now_thermalshock"); //小寇说这个作废了
        //煤流
//        map.put("coalflow", "dwd_zdsb_now_coalflow");
        //瓦斯抽采
        map.put("gasext", "dwd_zdsb_now_wscf");

        //快速掘进
        map.put("drivage", "dwd_zdsb_now_ksjj");

        //制氮
        map.put("nitrogen", "dwd_zdsb_now_nitrogen");
        return map;
    }

    public Map<String, String> setDevName() {
        Map<String, String> map = new HashMap<>();
        map.put("压风", "compressor");
        //排水
        map.put("主排水", "drainage");
        //通风
        map.put("通风", "fan");
        //煤流
        map.put("煤流", "coalflow");
        //铁路装车
//        map.put("railway", "dwd_zdsb_now_railway");
        //立井提升
        map.put("shaft", "dwd_zdsb_now_shaft");
        //斜井提升
        map.put("提升", "inclineShaft");
        //支架
        map.put("顶板", "support");
        //采煤
        map.put("综采", "mining");
        //协同开采
        map.put("协同开采", "thermalshock");
        //煤流
//        map.put("coalflow", "dwd_zdsb_now_coalflow");
        //瓦斯抽采
        map.put("瓦斯抽放", "gasext");

        //快速掘进
        map.put("综掘", "drivage");

        //制氮
        map.put("制氮", "nitrogen");
        return map;
    }

    public Map<String, String> setSysName() {
        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String> entry : setDevName().entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        return map;
    }

    @Override
    public Map queryCurrentByEquType(String equType, String apiPage, String mineCode) {
        Map<String, List<Map<String, String>>> data = new HashMap<>();
        List<EquPointTable> equPointTables = new ArrayList<>();
        if ("fan".equals(equType) && "150621011038".equals(mineCode)) {
            //拦截主通风的请求 去直接查询视图
//            long startTime = System.currentTimeMillis();
            equPointTables = equipmentMapper.queryCurrentByApiPage(apiPage);
//            long endTime = System.currentTimeMillis();
//            System.out.println("Query time: " + (endTime - startTime) + " ms");
        } else {
            equPointTables = equipmentMapper.queryCurrentByEquType(dbName.get(equType), equType, apiPage, mineCode);
        }
        String categoryIndex = "";//记录本次循环与上次循环是不是同一个数据对象
        for (EquPointTable equPointTable : equPointTables) {
            if ("nitrogen".equals(equType)) {
                if ("ST05_AI_39".equals(equPointTable.getTag()) || "ST05_AI_49".equals(equPointTable.getTag()) || "ST05_AI_59".equals(equPointTable.getTag())) {
                    String value = equPointTable.getValue();
                    if (StringUtils.isBlank(value)) {
                        BigDecimal divide = BigDecimal.valueOf(Double.parseDouble(value)).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP);
                        equPointTable.setValue(divide.doubleValue() + "");
                    }
                }
            }
            if (("KG".equals(equPointTable.getValueType()) || "BJ".equals(equPointTable.getValueType()) || "shearPosition".equals(equPointTable.getName())) && equPointTable.getValue() != null)
                equPointTable.setValue(Double.valueOf(equPointTable.getValue()).longValue() + "");//开关类去掉小数；支架位置去掉小数

            if (equPointTable.getValue() == null) equPointTable.setValue("--");
            if (data.get(equPointTable.getCategory()) == null) {
                Map<String, String> map = new HashMap<>();

                if ("定值，无需监测".equals(equPointTable.getRemark()) || "定值".equals(equPointTable.getRemark())) {
                    map.put(equPointTable.getName(), equPointTable.getTag());
                } else {
                    map.put(equPointTable.getName(), equPointTable.getValue());
                }
                List<Map<String, String>> list = new ArrayList<>();
                list.add(map);
                data.put(equPointTable.getCategory(), list);
            } else {
                List<Map<String, String>> maps = data.get(equPointTable.getCategory());
                if (categoryIndex.equals(equPointTable.getCategory() + equPointTable.getIndex())) {//与上一个是一个数据对象的数据
                    Map<String, String> map = maps.get(maps.size() - 1);
                    if (map.get(equPointTable.getName()) == null) {//无此属性
//                        map.put(equPointTable.getName(),equPointTable.getValue());
                        if ("定值，无需监测".equals(equPointTable.getRemark()) || "定值".equals(equPointTable.getRemark())) {
                            map.put(equPointTable.getName(), equPointTable.getTag());
                        } else {
                            map.put(equPointTable.getName(), equPointTable.getValue());
                        }
                    } else {//已经存在此属性
                        //判断 point_tag包含多个值处理
                        //多值有两种情况  第一种：,  第二种: |  ||
                        if (equPointTable.getTag().contains(",")) {
                            if (equPointTable.getTag().startsWith(equPointTable.getCode()))
                                map.put(equPointTable.getName(), equPointTable.getValue() + map.get(equPointTable.getName()));
                            if (equPointTable.getTag().endsWith(equPointTable.getCode()))
                                map.put(equPointTable.getName(), map.get(equPointTable.getName()) + equPointTable.getValue());
                        } else if (equPointTable.getTag().contains("|") || equPointTable.getTag().contains("||")) {
                            //如果开关量已经是1 则不再处理  如果是零则覆盖一下
                            String value = map.get(equPointTable.getName());
                            if (Integer.valueOf(value) == 0) {
                                map.put(equPointTable.getName(), equPointTable.getValue());
                            }
                        }
                    }
                } else {
                    Map<String, String> map = new HashMap<>();
//                    map.put(equPointTable.getName(), equPointTable.getValue());
                    if ("定值，无需监测".equals(equPointTable.getRemark()) || "定值".equals(equPointTable.getRemark())) {
                        map.put(equPointTable.getName(), equPointTable.getTag());
                    } else {
                        map.put(equPointTable.getName(), equPointTable.getValue());
                    }
                    maps.add(map);
                }
            }
            categoryIndex = equPointTable.getCategory() + equPointTable.getIndex();
        }

        return data;
    }

    @Override
    public List<EquipmentSwitchVo> equipmentSwitch() {
        List<EquipmentSwitchVo> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        List<CoalMineSysPointPo> coalMineSysPointPos = coalMineSysPointMapper.selectList(new LambdaQueryWrapper<CoalMineSysPointPo>().eq(CoalMineSysPointPo::getApiName, "runningState"));
        for (CoalMineSysPointPo coalMineSysPointPo : coalMineSysPointPos) {
            String category = coalMineSysPointPo.getApiCategory().split("-")[0];
            if (map.get(category) == null || !"1.0000".equals(map.get(category))) {//多个设备存在运行的就不用向下找了
                //开关量有一种或的关系
                EquipmentSwitchVo equipmentSwitchVo = new EquipmentSwitchVo();
                if (coalMineSysPointPo.getPointTag() == null) {
                    coalMineSysPointPo.setPointTag("");
                }
                if (coalMineSysPointPo.getPointTag().contains("|") || coalMineSysPointPo.getPointTag().contains("||")) {
                    //包含或的关系 则循环判断
                    List<EquipmentSwitchVo> voList = new ArrayList<>();
                    String[] split = new String[0];
                    if (coalMineSysPointPo.getPointTag().contains("||")) {
                        // ||这种情况
                        split = coalMineSysPointPo.getPointTag().split("\\|\\|");
                    } else {
                        // |这种情况
                        split = coalMineSysPointPo.getPointTag().split("\\|");
                    }
                    for (String tag : split) {
                        EquipmentSwitchVo vo = equipmentMapper.runningState(dbName.get(category), tag);
                        if (vo != null && vo.getRunState() != null) {
                            voList.add(vo);
                        }
                    }
                    Boolean run = false;
                    for (EquipmentSwitchVo switchVo : voList) {
                        if ("1.0000".equals(switchVo.getRunState())) {
                            //有开机情况
                            run = true;
                        }
                    }
                    equipmentSwitchVo = new EquipmentSwitchVo();
                    equipmentSwitchVo.setDevName(category);
                    if (run) {
                        equipmentSwitchVo.setRunState("1.0000");
                    } else {
                        equipmentSwitchVo.setRunState("0.0000");
                    }
                } else {
                    equipmentSwitchVo = equipmentMapper.runningState(dbName.get(category), coalMineSysPointPo.getPointTag());
                }
                if (equipmentSwitchVo != null) {
                    map.put(category, equipmentSwitchVo.getRunState());
                } else {
                    if (map.get(category) == null) {
                        map.put(category, null);
                    }
                }
            }

//            if (equipmentSwitchVo != null) {
//                equipmentSwitchVo.setDevName(coalMineSysPointPo.getDeviceName());
//            } else {
//                equipmentSwitchVo = new EquipmentSwitchVo();
//                equipmentSwitchVo.setDevName(category);
//            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            EquipmentSwitchVo equipmentSwitchVo = new EquipmentSwitchVo();
            equipmentSwitchVo.setDevName(entry.getKey());
            equipmentSwitchVo.setRunState(entry.getValue());
            list.add(equipmentSwitchVo);
        }
        return list;
    }

    @Override
    public List<EquipmentSwitchVo> equipmentSwitchByMineCode(String mineCode) {
        List<EquipmentSwitchVo> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        List<CoalMineSysPointPo> coalMineSysPointPos = coalMineSysPointMapper.selectList(new LambdaQueryWrapper<CoalMineSysPointPo>()
                .eq(CoalMineSysPointPo::getApiName, "runningState").eq(CoalMineSysPointPo::getMineCode, mineCode));
        for (CoalMineSysPointPo coalMineSysPointPo : coalMineSysPointPos) {
            String category = coalMineSysPointPo.getApiCategory().split("-")[0];
            if (map.get(category) == null || !"1.0000".equals(map.get(category))) {//多个设备存在运行的就不用向下找了
                EquipmentSwitchVo equipmentSwitchVo = equipmentMapper.runningStateByMineCode(dbName.get(category), coalMineSysPointPo.getPointTag(), mineCode);
                if (equipmentSwitchVo != null) {
                    map.put(category, equipmentSwitchVo.getRunState());
                } else {
                    if (map.get(category) == null) {
                        map.put(category, null);
                    }
                }
            }

//            if (equipmentSwitchVo != null) {
//                equipmentSwitchVo.setDevName(coalMineSysPointPo.getDeviceName());
//            } else {
//                equipmentSwitchVo = new EquipmentSwitchVo();
//                equipmentSwitchVo.setDevName(category);
//            }
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            EquipmentSwitchVo equipmentSwitchVo = new EquipmentSwitchVo();
            equipmentSwitchVo.setDevName(entry.getKey());
            equipmentSwitchVo.setRunState(entry.getValue());
            list.add(equipmentSwitchVo);
        }
        return list;
    }

    public List<CoalMineSysPointPo> getStartStopByEquipment(String equipmentType, String apiPage) {
        LambdaQueryWrapper<CoalMineSysPointPo> lambdaQueryWrapper = new LambdaQueryWrapper<CoalMineSysPointPo>()
                .like(CoalMineSysPointPo::getApiCategory, equipmentType)
                .eq(CoalMineSysPointPo::getApiName, "runningState");
        if (StringUtils.isNotBlank(apiPage)) {
            lambdaQueryWrapper = lambdaQueryWrapper.eq(CoalMineSysPointPo::getApiPage, apiPage);
        }
        List<CoalMineSysPointPo> coalMineSysPointPos = coalMineSysPointMapper.selectList(lambdaQueryWrapper);
        for (CoalMineSysPointPo coalMineSysPointPo : coalMineSysPointPos) {
            EquipmentSwitchVo equipmentSwitchVo = equipmentMapper.runningState(dbName.get(equipmentType), coalMineSysPointPo.getPointTag());
            if (equipmentSwitchVo != null) {
                coalMineSysPointPo.setPointCurrentValue(equipmentSwitchVo.getRunState());
            }
        }
        coalMineSysPointPos = coalMineSysPointPos.stream().sorted(Comparator.comparing(CoalMineSysPointPo::getDeviceArrayIndex)).collect(Collectors.toList());
        return coalMineSysPointPos;
    }

    @Override
    public ChartVo zjylChart(String mineCode) {
        ChartVo chartVo = new ChartVo();
        chartVo.setValeus(new ArrayList<>());
        chartVo.setXData(new ArrayList<>());
        List<Map<String, BigDecimal>> maps = new ArrayList<>();
        if ("150621011038".equals(mineCode)) {
            //高头窑煤矿
            maps = equipmentMapper.zjylChart1();
        } else if ("620824009734".equals(mineCode)) {
            //砚北煤矿
//            maps= equipmentMapper.zjylChart();

            //获取配置文件中的动态压力字符串  支架压力，立柱压力的等区别
            String supportStr = coalMineSysPointMapper.supportTypeName("1", mineCode);
            maps = equipmentMapper.zjylChartStr(supportStr);
        }
        for (Map<String, BigDecimal> map : maps) {
            chartVo.getXData().add(String.valueOf(map.get("point_code")));
            chartVo.getValeus().add(map.get("point_value"));
        }
        return chartVo;
    }

    public List<AlarmMessageItemVo> alarmMessageItem(String equipmentType) {

        List<AlarmMessageItemVo> list = new ArrayList<>();
        String tableName = dbName.get(devName.get(equipmentType));
        Map<String, String> sysName = setSysName();
        if (StringUtils.isNotBlank(tableName)) {
            List<EquPointTable> equPointTables = equipmentMapper.alarmMessageItem(tableName, equipmentType);
            for (EquPointTable equPointTable : equPointTables) {
                AlarmMessageItemVo vo = new AlarmMessageItemVo();
                String category = equPointTable.getCategory().split("-")[0];
                vo.setAlarmType(sysName.get(category));
                vo.setKey(equPointTable.getTag());
                vo.setAlarmTime(equPointTable.getDataTime());
                vo.setContent(equPointTable.getTag() + "点位异常");
                list.add(vo);
            }
        } else {
            for (Map.Entry<String, String> entry : dbName.entrySet()) {
                String value = entry.getValue();
                List<EquPointTable> equPointTables = equipmentMapper.alarmMessageItem(value, equipmentType);
                for (EquPointTable equPointTable : equPointTables) {
                    AlarmMessageItemVo vo = new AlarmMessageItemVo();
                    String category = equPointTable.getCategory().split("-")[0];
                    vo.setAlarmType(sysName.get(category));
                    vo.setKey(equPointTable.getTag());
                    vo.setAlarmTime(equPointTable.getDataTime());
                    vo.setContent(equPointTable.getTag() + "点位异常");
                    list.add(vo);
                }
            }
        }

        return list;
    }

    @Override
    public ChartOperationRateVO operationRate() {

        DateTime startTime = DateUtil.beginOfMonth(new Date());
        DateTime endTime = DateUtil.endOfMonth(new Date());
        Long offSet = DateUtil.betweenDay(startTime, endTime, true);

        Map<String, OperationRateVO> res = new TreeMap<>();
        // todo 没测试数据，逻辑待确认
        List<Map<String, Object>> queryResult = equipmentMapper.operationRate(DateUtil.formatDate(startTime), Math.toIntExact(offSet));
        queryResult.forEach(n -> {
            String key = (String) n.get("date_time");
            if (res.get(key) == null) {
                res.put(key, new OperationRateVO(key));
            }
            if (n.get("equipment_flag") != null) {
                OperationRateVO vo = res.get(key);
                BigDecimal rate = (BigDecimal) n.get("rate");
                Integer flag = (Integer) n.get("equipment_flag");
                switch (flag) {
                    case 0:
                        vo.setCoalCutterValue(rate);
                        break;
                    case 1:
                        vo.setTunnelBorerValue(rate);
                        break;
                    default:
                        break;
                }
            }
        });

        ChartOperationRateVO result = new ChartOperationRateVO();
        result.setXName(res.values().stream().map(OperationRateVO::getXName).collect(Collectors.toList()));
        result.setCoalCutterValue(res.values().stream().map(OperationRateVO::getCoalCutterValue).collect(Collectors.toList()));
        result.setTunnelBorerValue(res.values().stream().map(OperationRateVO::getTunnelBorerValue).collect(Collectors.toList()));
        result.setBeltConveyorValue(res.values().stream().map(OperationRateVO::getBeltConveyorValue).collect(Collectors.toList()));
        result.setCompressorValue(res.values().stream().map(OperationRateVO::getCompressorValue).collect(Collectors.toList()));
        result.setInclineShaftValue(res.values().stream().map(OperationRateVO::getInclineShaftValue).collect(Collectors.toList()));
        result.setVentilatorValue(res.values().stream().map(OperationRateVO::getVentilatorValue).collect(Collectors.toList()));
        result.setPumpValue(res.values().stream().map(OperationRateVO::getPumpValue).collect(Collectors.toList()));

        return result;
    }

    @Override
    public ChartCggdVO cggdChart(String mineCode) {

        ChartCggdVO chartCggdVO = new ChartCggdVO();
        chartCggdVO.setXData(new ArrayList<>());
        chartCggdVO.setCggdValue(new ArrayList<>());
        chartCggdVO.setZjylValue(new ArrayList<>());
        List<Map<String, BigDecimal>> maps = new ArrayList<>();
        if ("150621011038".equals(mineCode)) {
            maps = equipmentMapper.cggdChart1();
        } else {
            //获取配置文件中支架压力的动态文本值  立柱压力
            String supportStr = coalMineSysPointMapper.supportTypeName("1", mineCode);
            if (StringUtils.isEmpty(supportStr)) {
                maps = equipmentMapper.cggdChart();
            } else {
                //有动态值
                maps = equipmentMapper.cggdChartByPressure(supportStr);
            }

        }
        //

        for (Map<String, BigDecimal> map : maps) {

            chartCggdVO.getXData().add(String.valueOf(map.get("point_code")).trim());
            if (!"150621011038".equals(mineCode)) {
                chartCggdVO.getCggdValue().add(map.get("cggd"));
            }
            chartCggdVO.getZjylValue().add(map.get("zjyl"));
        }
        return chartCggdVO;
    }

    @Override
    public MiningChartVO miningChart(String mineCode) {
        Date date = new Date();
        DateTime startTime = DateUtil.beginOfDay(date);
        Date lastDate = DateUtils.addDays(new Date(), -1);
        DateTime lastStartTime = DateUtil.beginOfDay(lastDate);
        List<Map<String, BigDecimal>> maps = new ArrayList<>();
        List<Map<String, BigDecimal>> lastMaps = new ArrayList<>();
        MiningChartVO miningChartVO = new MiningChartVO();
        miningChartVO.setXData(new ArrayList<>());
        miningChartVO.setValueYesterday(new ArrayList<>());
        miningChartVO.setValueToday(new ArrayList<>());

        if ("150621011038".equals(mineCode)) {
            lastMaps = equipmentMapper.mining1(DateUtil.formatDate(lastStartTime));
            maps = equipmentMapper.mining1(DateUtil.formatDate(startTime));
        } else if ("620824009734".equals(mineCode)) {
            lastMaps = equipmentMapper.mining(DateUtil.formatDate(lastStartTime));
            maps = equipmentMapper.mining(DateUtil.formatDate(startTime));
        } else if ("150781013671".equals(mineCode)) {
            lastMaps = equipmentMapper.mining2(DateUtil.formatDate(lastStartTime));
            maps = equipmentMapper.mining2(DateUtil.formatDate(startTime));
        }
        for (Map<String, BigDecimal> map : lastMaps) {
            miningChartVO.getXData().add(String.valueOf(map.get("date_time")).substring(11, 16));
            miningChartVO.getValueYesterday().add(map.get("point_value").compareTo(BigDecimal.ZERO) > 0 ? map.get("point_value") : null);
        }
        for (Map<String, BigDecimal> map : maps) {
            miningChartVO.getValueToday().add(map.get("point_value").compareTo(BigDecimal.ZERO) > 0 ? map.get("point_value") : null);
        }
        return miningChartVO;
    }

    @Override
    public List<DataStateVo> getMaxTime(String mineCode, String companyCode, String sysName) {
        String s = devName.get(sysName);
        if (s == null) {
            return new ArrayList<>();
        }
//        String sql="SELECT mine_code as mineCode,max(data_time) as maxTime  FROM "+dbName.get(s)+" where 1=1 %s %s group by mine_code";
//        if(StringUtils.isNotBlank(mineCode)){
//            mineCode ="and mine_code='"+mineCode+"' ";
//        }else{
//            mineCode="";
//        }
//        if(StringUtils.isNotBlank(companyCode)&&StringUtils.isBlank(mineCode)){
//            companyCode ="and company_code='"+companyCode+"' ";
//        }else {
//            companyCode="";
//        }
        List<DataStateVo> query = equipmentMapper.getMaxTime(mineCode, companyCode, dbName.get(s));
        return query;
    }

    /**
     * 生产报表-根据生产设备类型获取生产报表
     *
     * @param productionStatementDto
     * @return
     */
    @Override
    public List<ProductionStatementVo> getProductionStatementBydeviceType(ProductionStatementDto productionStatementDto) {
        if (productionStatementDto.getStartDate() == null) {
            //如果开始时间为空 则设置前一天的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            productionStatementDto.setStartDate(calendar.getTime());
        }
        if (productionStatementDto.getEndDate() == null) {
            //如果结束时间为空则设置当前时间
            productionStatementDto.setEndDate(new Date());
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = sdf.format(productionStatementDto.getEndDate());
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date parse = sdf1.parse(dateString + " 23:59:59");
                productionStatementDto.setEndDate(parse);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }

        //获取生产系统设备词典列表
        List<SysDictData> coverageOSList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "biz_equipment_device_type");

        //判断是否设备编码是否存在，不存在就查询所有的设备列表，存在就只查询一个
        List<ProductionStatementEquipmentStartDayDto> equipmentStartDayPoAllList = new ArrayList<>();
        if (StringUtils.isNotBlank(productionStatementDto.getDeviceTypeCode())) {
            //存在编码
            equipmentStartDayPoAllList = equipmentStartDayMapper.getProductionStatementBydeviceType(productionStatementDto);
        } else {
            //不存在编码
            //遍历所有的列表
            for (SysDictData sysDictData : coverageOSList) {
                //设置编码
                productionStatementDto.setDeviceTypeCode(sysDictData.getDictValue());
                List<ProductionStatementEquipmentStartDayDto> equipmentStartDayPoList = equipmentStartDayMapper.getProductionStatementBydeviceType(productionStatementDto);
                for (ProductionStatementEquipmentStartDayDto productionStatementEquipmentStartDayDto : equipmentStartDayPoList) {
                    //将查询到的子系统 遍历到全组内
                    equipmentStartDayPoAllList.add(productionStatementEquipmentStartDayDto);
                }
            }
        }
        return equipmentStartDayPoAllList.stream().map(t -> {
            ProductionStatementVo productionStatementVo = new ProductionStatementVo();
            //生产系统编码
            productionStatementVo.setProductionSystemCode(t.getEquipmentFlag().toString());
            //生产系统名称
            coverageOSList.forEach(sysDictData -> {
                if (sysDictData.getDictValue().equals(t.getEquipmentFlag().toString())) {
                    productionStatementVo.setProductionSystemName(sysDictData.getDictLabel());
                }
            });
            //生产系统子设备名称
            productionStatementVo.setProductionSystemDeviceName(t.getDeviceName());
            //通讯中断-时长
            productionStatementVo.setInterruptDuration(this.minutConversion(new BigDecimal(t.getInterruptDuration())));
            //通讯中断-占比
            productionStatementVo.setInterruptRatio(t.getInterruptRatio() + "%");
            //通讯中断-分钟
            productionStatementVo.setInterruptMinute(t.getInterruptDuration());

            //停机-时长
            productionStatementVo.setMachineHaltDuration(this.minutConversion(new BigDecimal(t.getMachineHaltDuration())));
            //停机-占比
            productionStatementVo.setMachineHaltRatio(t.getMachineHaltRatio() + "%");
            //停机-分钟
            productionStatementVo.setMachineHaltMinute(t.getMachineHaltDuration());

            //运行-时长
            productionStatementVo.setRunningDuration(this.minutConversion(new BigDecimal(t.getRunningDuration())));
            //运行-占比
            productionStatementVo.setRunningRatio(t.getRunningRatio() + "%");
            //运行-分钟
            productionStatementVo.setRunningMinute(t.getRunningDuration());
            //耗电量
            productionStatementVo.setPowerConsumption("---");
            //故障次数
            productionStatementVo.setFailureNumber("---");
            //故障诊断次数
            productionStatementVo.setFailureDiagnosisNumber("---");
            //维保次数
            productionStatementVo.setMaintenanceNumber("---");
            //煤矿编码
            productionStatementVo.setMineCode(t.getMineCode());
            //获取煤矿信息
            SysOrganization sysOrganization = RedisUtils.getCacheObject(Constants.SYS_CODE_KEY + t.getMineCode());
            if (sysOrganization == null) {
                productionStatementVo.setMineName("获取煤矿编码词典有误，请检查词典");
            } else {
                productionStatementVo.setMineName(sysOrganization.getOrgName());
            }
            //煤矿名称
            return productionStatementVo;
        }).collect(Collectors.toList());
    }

    /**
     * List<FanSystemVolumeAndSpeedDto>
     *
     * @param mineCode
     * @return
     */
    @Override
    public List<FanSystemVolumeAndSpeedDto> getFanSystemVolumeAndSpeedList(String mineCode) {

        List<FanSystemVolumeAndSpeedDto> fanSystemVolumeAndSpeedDtos = new ArrayList<>();
        //获取术语表中的tag数据值
        List<CoalMineSysPointPo> coalMineSysPointPos = coalMineSysPointMapper.selectVolumeAndSpeedTagList(mineCode);
        //根据api_category 分组 白家渠和赵家渠
        Map<String, List<CoalMineSysPointPo>> collect = coalMineSysPointPos.stream().collect(Collectors.groupingBy(CoalMineSysPointPo::getApiCategory));
        for (Map.Entry<String, List<CoalMineSysPointPo>> entry : collect.entrySet()) {
            String k = entry.getKey();
            List<CoalMineSysPointPo> v = entry.getValue();
            //机房的数据
            //根据device_array_index 进行分组  一号风机二号风机
            Map<String, List<CoalMineSysPointPo>> collect1 = v.stream().collect(Collectors.groupingBy(CoalMineSysPointPo::getDeviceArrayIndex));
            collect1.forEach((k1, v1) -> {
                FanSystemVolumeAndSpeedDto fanSystemVolumeAndSpeedDto = new FanSystemVolumeAndSpeedDto();
                //获取风机状态 风速 运行状态
                fanSystemVolumeAndSpeedDto.setLocation(v1.get(0).getApiPage());
                fanSystemVolumeAndSpeedDto.setDeviceName(v1.get(0).getDeviceName());
                v1.forEach(t -> {
                    if (t.getApiName().equals("runningState")) {
                        fanSystemVolumeAndSpeedDto.setStatus(t.getPointCurrentValue());
                    } else if (t.getApiName().equals("windSpeedValue")) {
                        fanSystemVolumeAndSpeedDto.setSpeed(t.getPointCurrentValue());
                    } else if (t.getApiName().equals("windAmountValue")) {
                        fanSystemVolumeAndSpeedDto.setVolume(t.getPointCurrentValue());
                    }
                });
                fanSystemVolumeAndSpeedDto.setMineCode(v1.get(0).getMineCode());
                fanSystemVolumeAndSpeedDtos.add(fanSystemVolumeAndSpeedDto);
            });
        }
        return fanSystemVolumeAndSpeedDtos;

    }

    /**
     * 传递一个数值类型 分钟数
     *
     * @param minutes
     * @return 返回 **天**时**秒 格式的数据
     */
    public String minutConversion(BigDecimal minutes) {
//            int minutes = 1500;
//            int days = minutes / (24 * 60); // 计算天数
//            int hours = (minutes % (24 * 60)) / 60; // 计算小时数
//            int remainingMinutes = minutes % 60; // 计算剩余的分钟数
//            System.out.println(days + "天 " + hours + "小时 " + remainingMinutes + "分钟");

        //minutes 带小数的分钟数
        BigDecimal daysDecimal = minutes.divide(new BigDecimal("1440"), 0, BigDecimal.ROUND_DOWN); // 计算天数
        int days = daysDecimal.intValue();
        BigDecimal remainingMinutesDecimal = minutes.remainder(new BigDecimal("1440")); // 计算剩余分钟数

        BigDecimal hoursDecimal = remainingMinutesDecimal.divide(new BigDecimal("60"), 0, BigDecimal.ROUND_DOWN); // 计算小时数
        int hours = hoursDecimal.intValue();

        BigDecimal remainingMinutes = remainingMinutesDecimal.remainder(new BigDecimal("60")); // 计算剩余分钟数

        return days + "天" + hours + "小时" + remainingMinutes + "分钟";
    }

}
